<template>
	<view class="evaluate-poly-component">
		<scroll-view
			scroll-y="true"
			:enable-passive="true"
			:scroll-into-view="scrollView"
			:scroll-with-animation="true"
			class="evaluate-poly-scroll-view"
		>
			<view
				v-if="selectList.length"
				class="evaluate-params-list"
			>
				<view
					v-for="(item, index) in selectList"
					:key="item.conftype"
				>
					<view v-if="item.show_status" class="evaluate-item">
						<view v-if="item.confTypeName" class="evaluate-category-name">{{ item.confTypeName }}</view>
						<view
							:class="['evaluate-questions', {
								'no-placeholder': !item.confTypeName
							}]"
						>
							<template
								v-for="(child, idx) in item.questions"
							>
								<view
									v-if="child.show_status"
									:id="'questionView-' + child.id"
									:key="child.id"
									class="evaluate-question-item"
								>
									<view
										class="evaluate-question-title"
										@click="selectQuestion({
											conftypeIndex: index,
											qIndex: idx
										})"
									>
										<view class="evaluate-question-name">{{ child.name }}</view>
										<view
											v-if="child.course && child.course.step && child.course.step.length > 0"
											class="evaluate-question-tips"
											@click.stop="showPreview(child.course)"
										>
											<view v-if="child.conftype === '1'" class="evaluate-tips">
												<text>查询方式</text>
												<image class="icon-right" src="https://s1.huishoubao.com/static/business-component/icon_right_blue.png"></image>
											</view>
											<view v-else class="evaluate-tips">
												<image class="icon-question" src="https://s1.huishoubao.com/static/business-component/icon_question.png"></image>
											</view>
										</view>
										<view class="select-answer-name">{{ child.selectName || '' }}</view>
										<image
											src="https://s1.huishoubao.com/static/business-component/icon_down.png"
											:class="['icon-down', {
												fold: child.fold
											}]"
										></image>
									</view>
									<view
										v-show="!child.fold && child.question.length"
										:class="['evaluate-answers', {
											single: child.single !== '2',
											multiple: child.single === '2'
										}]"
									>
										<view
											v-for="(v, i) in child.question"
											:key="v.id"
											class="evaluate-answers-item"
											@click.stop="selectOption({
												isFinally: idx === item.questions.length - 1,
												conftype: item.conftype,
												conftypeIndex: index,
												qId: child.id,
												qName: child.name,
												qIndex: idx,
												aId: v.id,
												aName: v.name,
												aIndex: i
											})"
										>
											<view class="evaluate-answers-body">
												<view
													:class="['evaluate-answers-content', {
														active: v.selected
													}]"
													:style="{
														color: v.selected ? color : '#2c2c2c',
														background: v.selected ? background : '#f7f7f7',
														borderColor: v.selected ? borderColor : '#f7f7f7'
													}"
												>
													<view
														v-if="child.single !== '2' && v.course && v.course.step && v.course.step.length"
														class="answer-image-body"
														@click.stop="showPreview(v.course)"
													>
														<view class="answer-image">
															<image
																v-if="v.course.step[0].pic && v.course.step[0].pic.length"
																mode="widthFix"
																class="icon-answer-image"
																:src="'https://s1.huishoubao.com/img/phone/' + v.course.step[0].pic[0]"
															></image>
															<image class="icon-image-zoom" src="https://s1.huishoubao.com/static/business-component/icon_image_zoom.png"></image>
														</view>
													</view>
													<view
														:class="['answer-content', {
															crowded: !v.course && (v.desc || v.alias_name)
														}]"
													>
														<view class="answer-name">
															<view
																v-if="child.single === '2' && v.course && v.course.step && v.course.step.length"
																class="multiple-answer-name"
															>
																<image
																	src="https://s1.huishoubao.com/static/business-component/icon_question.png"
																	class="icon-question"
																	@click.stop="showPreview(v.course)"
																></image>
																<text>{{ v.name }}</text>
															</view>
															<text v-else>{{ v.name }}</text>
														</view>
														<view
															v-show="(v.desc || v.alias_name) && child.single !== '2'"
															class="answer-rate"
														>
															{{ v.desc || v.alias_name }}
														</view>
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</template>
						</view>
					</view>
				</view>
			</view>
			<view
				v-if="selectList.length === 0"
				class="option-loading"
			>
				<view v-if="loading">
					<!-- #ifndef MP-DINGTALK -->
					<uv-loading-icon size="50rpx" :color="borderColor" />
					<!-- #endif -->
				</view>
				<view v-else>
					<hsb-business-no-options :text="errMsg || '暂无估价选项'" />
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
export default {
	name: 'EvaluatePoly',
	props: {
		optionList: Array,
		loading: Boolean,
		color: {
		  type: String,
		  default: '#2C2C2C'
		},
		background: {
		  type: String,
		  default: 'rgba(255, 225, 0, 0.8)'
		},
		borderColor: {
		  type: String,
		  default: 'rgba(255, 225, 0, 0.8)'
		},
		transition: {
		  type: Number,
		  default: 350
		},
		showDeblock: {
		  type: Boolean,
		  default: true
		},
		errMsg: String
	},
	watch: {
		optionList (options) {
			this.selectList = JSON.parse(JSON.stringify(options))
			this.computedSelectData()
		}
	},
	data () {
		return {
			selectList: [],
			scrollView: '',
			isMovingStatus: false
		}
	},
	methods: {
		/**
		 * 折叠/展开问题项
		 * @param {Object.conftypeIndex} 大类下标
		 * @param {Object.qIndex} 问题项下标
		 */
		selectQuestion ({ conftypeIndex, qIndex }) {
		  if (this.isMovingStatus) return
		  // 当前大类下的当前问题项信息
		  const questionInfo = this.selectList[conftypeIndex].questions[qIndex]
		  // 当前大类下的当前问题项下答案项列表
		  const answerList = questionInfo.question || []
		  const selected = answerList.some(e => e.selected)
		  if (selected && questionInfo.single !== '2') {
		    questionInfo.fold = !questionInfo.fold
		  }
		},
		/**
		 * 选中答案项
		 * @param {Object.conftypeIndex} 大类下标
		 * @param {Object.qId} 问题项ID
		 * @param {Object.qName} 问题项名称
		 * @param {Object.qIndex} 问题项下标
		 * @param {Object.aId} 答案项ID
		 * @param {Object.aName} 答案项名称
		 * @param {Object.aIndex} 答案项下标
		 * @param {Object.isFinally} 是否为类下的最后一个问题项
		 */
		selectOption ({ conftypeIndex, qId, qIndex, aId, aIndex, isFinally }) {
		  if (this.isMovingStatus) return
		  if (aId === '100049') {
				return this.$emit('icloubLock')
		  }
		  // 当前大类信息
		  const conftypeInfo = this.selectList[conftypeIndex]
		  // 当前大类下的当前问题项信息
		  const questionInfo = conftypeInfo.questions[qIndex]
		  // 当前大类下的下一个问题项信息
		  const nextQuestionInfo = conftypeInfo.questions[qIndex + 1]
		  // 下一个大类信息
		  const nextConftypeInfo = this.selectList[conftypeIndex + 1]
		  // 单选/多选
		  if (questionInfo.single === '2') {
		    // 多选问题项
		    const answerInfo = questionInfo.question[aIndex]
		    answerInfo.selected = !answerInfo.selected
		    questionInfo.question.forEach(item => {
		      if (item.id === aId) return
		      if (answerInfo.single === '2') {
		        if (item.single === '1') {
		          item.selected = false
		        }
		      } else {
		        item.selected = false
		      }
		    })
		  } else {
		    // 单选问题项
		    let matchOptionList = []
		    let removeOptionList = []
		    // 选中当前答案项，且移除其他选中答案项
		    questionInfo.question.forEach(item => {
		      if (item.id === aId) {
		        item.selected = true
		        // 该选项为联动答案项
		        if (item.default_option_questions && item.default_option_questions.length) {
		          matchOptionList = [...item.default_option_questions]
		        }
		      } else {
		        if (item.selected) {
		          item.selected = false
		          // 该选项为联动答案项
		          if (item.default_option_questions && item.default_option_questions.length) {
		            removeOptionList = removeOptionList.concat(item.default_option_questions)
		          }
		        }
		      }
		    })
		    // 折叠当前问题项
		    questionInfo.fold = true
		    // 匹配到选项联动列表
		    if (matchOptionList.length || removeOptionList.length) {
		      this.selectList.forEach((item, index) => {
		        // 不处理当前大类之前的数据
		        if (index < conftypeIndex) return
		        item.questions.forEach((child, idx) => {
		          // 不处理当前问题项之前的数据
		          const qIdx = index > conftypeIndex ? 0 : qIndex
		          if (idx < qIdx) return
		          if (removeOptionList.includes(child.id)) {
		            item.show_status = true
		            child.default_option = false
		            child.show_status = true
		          }
		          if (matchOptionList.includes(child.id)) {
		            child.default_option = true
		            child.show_status = false
		            child.fold = false
		            if (child.selectName) {
		              child.selectName = ''
		              child.question.forEach(v => {
		                if (v.selected) {
		                  v.selected = false
		                  // 如果当前答案项命中联动选项，则将联动的问题项放开
		                  if (v.default_option_questions && v.default_option_questions.length) {
		                    removeOptionList = removeOptionList.concat(v.default_option_questions)
		                  }
		                }
		              })
		            }
		          }
		        })
		        if (item.questions.every(e => e.default_option)) {
		          item.show_status = false
		        }
		      })
		    }
		  }
		  // 选中的答案项名称
		  questionInfo.selectName = questionInfo.question.filter(e => e.selected).map(e => e.name).join('、')
		  // 记录下一个滚动id
		  let scrollViewId = ''
		  // 是否为当前大类下的最后一个问题项
		  if (isFinally) {
		    if (nextConftypeInfo) {
		      // 下一个大类下的第一个问题项不为联动问题项
		      if (!nextConftypeInfo.questions[0].default_option) {
		        nextConftypeInfo.show_status = true
		        nextConftypeInfo.questions[0].show_status = true
		        scrollViewId = `questionView-${nextConftypeInfo.questions[0].id}`
		      } else {
		        const { index, idx, id } = this.searchNextQuestion(conftypeIndex + 1)
		        if (index >= 0 && idx >= 0 && id) {
		          this.selectList[index].show_status = true
		          this.selectList[index].questions[idx].show_status = true
		          scrollViewId = `questionView-${this.selectList[index].questions[idx].id}`
		        }
		      }
		    }
		  } else {
		    if (!nextQuestionInfo.default_option) {
		      scrollViewId = `questionView-${nextQuestionInfo.id}`
		      nextQuestionInfo.show_status = true
		    } else {
		      const { index, idx, id } = this.searchNextQuestion(conftypeIndex, qIndex + 1)
		      if (index >= 0 && idx >= 0 && id) {
		        this.selectList[index].show_status = true
		        this.selectList[index].questions[idx].show_status = true
		        scrollViewId = `questionView-${this.selectList[index].questions[idx].id}`
		      }
		    }
		  }
		  this.selectList = [].concat(this.selectList)
		  this.computedSelectData()
		  if (!scrollViewId) return
		  if (scrollViewId === this.scrollView) {
		    this.scrollView = ''
		  }
			this.$nextTick(() => {
				this.scrollView = scrollViewId
			})
		},
		/**
		 * 找到下一个非联动的问题项
		 * @param {Number} conftypeIndex 大类下标
		 * @param {Number} qIndex 问题项下标
		 */
		searchNextQuestion (conftypeIndex = 0, qIndex = 0) {
		  const result = { index: -1, idx: -1, id: '' }
		  for (let index = conftypeIndex; index < this.selectList.length; index++) {
		    let isExit = false
		    let firstQIndex = index > conftypeIndex ? 0 : qIndex
		    for (let idx = firstQIndex; idx < this.selectList[index].questions.length; idx++) {
		      if (!this.selectList[index].questions[idx].default_option) {
		        result.index = index
		        result.idx = idx
		        result.id = this.selectList[index].questions[idx].id
		        isExit = true
		        break
		      }
		    }
		    if (isExit) break
		  }
		  return result
		},
		/**
		 * 计算选项选中数据
		 */
		computedSelectData () {
		  let total = 0
		  let selectLen = 0
		  this.selectList.forEach(item => {
		    if (item.conftype !== '3') {
		      total += item.questions.filter(e => !e.default_option).length
		    }
		    item.questions.forEach(child => {
		      if (child.selectName && item.conftype !== '3') {
		        selectLen++
		      }
		    })
		  })
		  this.$emit('change', { total, selectLen })
		},
		/**
		 * 显示图文教程
		 * @param {Object} courseInfo 图文信息
		 */
		showPreview (courseInfo) {
			this.$emit('paramsPreview', courseInfo)
		}
	}
}
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>